<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Asymptix\HtmlDomParser\HtmlDomParser;
use Illuminate\Support\Facades\Log;
use App\Jobs\updateSectionsByUrl;
use App\Models\Book;
use App\Models\Operation;
use App\Models\Section;

class getBookSectionsFromBiquge implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	private $url;
	private $book;
	
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($url, Book $book) {
		$this->url = $url;
		$this->book = $book;
	}
	
	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		if($this->attempts() >= 5) {
			Log::info('请求超过五次，均失败！');
			Operation::create([
				'action' => '小说更新-队列-请求失败',
				'content' => $book->name.' => 请求超过五次，均失败！'
			]);
			$this->delete();
			return 0;
		}
		
		$book = $this->book;
		$html = new HtmlDomParser();
		$html->loadUrl($this->url);
		$sections = $html->find('dl dd');
		$cSections = count($sections) - 9;
// 		if($cSections >= $book->sections->count()) {
		if(true) {
			$i=0;
// 			$num = $book->completed ? ($book->sections->count() + 9) : 9;
			$num = 9;
			foreach ($sections as $section) {
				$i++;
				if($i <= $num) continue;
				if($book->completed) {
					$st = Section::select(['name'])
							->where('book_id', $book->id)
							->where('order', (int)($i - 9))->first();
					if($st->name == $section->find('a', 0)->plaintext) continue;
				}
				dispatch(new updateSectionsByUrl($section->find('a', 0)->href, $i - 9, $cSections, $book));
			}
			$book->completed = true;
			$book->recover = false;
			$book->save();
			Log::info($book->name.' => 加入队列完成，需更新： '.($i-$num).' 章');
			Operation::create([
				'action' => '小说更新-队列',
				'content' => $book->name.' => 加入队列完成，需更新： '.($i-$num).' 章',
			]);
		}else {
			Log::info($book->name.' => 无需更新');
			Operation::create([
				'action' => '小说更新-队列',
				'content' => $book->name.' => 无需更新'
			]);
		}
		usleep(800000);
		return 0;
	}
}
